package com.alex.java8_04;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

import org.junit.Test;

public class TestForkJoin {

	/**
	 * Fork-Join框架
	 */
	@Test
	public void test1() {
		long start = System.currentTimeMillis();

		ForkJoinPool pool = new ForkJoinPool();
		ForkJoinTask<Long> task = new ForkJoinCalculate(0L, 10000000000L);// 当计算的值很小时，test2耗时比test1耗时还要短。计算值越大，越能体现test1比test2的快速性

		long sum = pool.invoke(task);
		System.out.println(sum);

		long end = System.currentTimeMillis();

		System.out.println("耗费的时间为: " + (end - start));
	}

	/**
	 * 普通for循环
	 */
	@Test
	public void test2() {
		long start = System.currentTimeMillis();

		long sum = 0L;

		for (long i = 0L; i <= 10000000000L; i++) {
			sum += i;
		}

		System.out.println(sum);

		long end = System.currentTimeMillis();

		System.out.println("耗费的时间为: " + (end - start));
	}

	/**
	 * Java并行流
	 */
	@Test
	public void test3() {
		long start = System.currentTimeMillis();

		Long sum = LongStream.rangeClosed(0L, 10000000000L).parallel().sum();

		System.out.println(sum);

		long end = System.currentTimeMillis();

		System.out.println("耗费的时间为: " + (end - start)); // 2061-2053-2086-18926
	}

}
